package com.af.security.auth.util.listener;

import com.af.security.auth.login.lock.LoginFailureCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

/**
 * @author : zhenyun.su
 * @since : 2020/03/26
 * @common : 监听密码错误，触发在缓存中记录失败次数
 */

@Component
public class AfBadCredentialEventListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
    private static final Logger logger = LoggerFactory.getLogger(AfBadCredentialEventListener.class);

    private LoginFailureCache loginFailureCache;

    public AfBadCredentialEventListener(LoginFailureCache loginFailureCache) {
        this.loginFailureCache = loginFailureCache;
    }

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent authenticationFailureBadCredentialsEvent) {
        try{
//        WebAuthenticationDetails authDetails = (WebAuthenticationDetails)authenticationFailureBadCredentialsEvent.getAuthentication().getDetails();
            String username=  authenticationFailureBadCredentialsEvent.getAuthentication().getPrincipal().toString();
            logger.debug("authentication failure,  Log+"+ username+" in failed");
            loginFailureCache.loginFailed(username);
        }catch(Exception e){
            logger.error("AuthenticationFailureBadCredentialsEvent failed: {}", e);
        }
    }
}
